import request from '../utils/request.js'
import jweixin from 'jweixin-module'

import moment from 'moment';
import config from '../utils/config.js'

export function formatDate(timestamp) {
	return moment(timestamp).format('YYYY-MM-DD');
};

/**
 * @param {Object} name
 * 名称脱敏
 */
export function desensitizeName(name) {
    if (!name || name.length  < 2) return name; // 非字符串或长度不足不处理 
 
    // 两字姓名：首字明文 + 星号（如“张三” → “张*”）
    if (name.length  === 2) {
        return name.charAt(0)  + '*';
    }
 
    // 三字及以上：首字明文 + 中间星号 + 尾字明文（如“张无忌” → “张*忌”）
    const firstChar = name.charAt(0); 
    const lastChar = name.charAt(name.length  - 1);
    const stars = '*'.repeat(name.length  - 2); // 星号数量 = 总长度-2 
    return firstChar + stars + lastChar;
}
 

export async function getOpenid() {
	let openid = uni.getStorageSync("openid");
	if (!openid) {
		openid = await getCode();
	}
	return openid
}
async function getCode() {
	let code = "";
	let local = window.location.href;
	let scope = "snsapi_base"; //静默授权 用户无感知
	code = getUrlCode().code;
	if (code == null || code === "") {
		window.location.replace(
			`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${config.appId}&redirect_uri=${encodeURIComponent(local)}&response_type=code&scope=${scope}#wechat_redirect`
		)
	} else {
		return await getOpenidByCode(code);
	}
}


async function getOpenidByCode(code) {
	console.log("获取openid==================")
	const res = await request({
		method: 'POST',
		header: {
			"Content-Type": "application/json"
		},
		data: {
			code
		},
		url: '/appoint/getOpenInfo'
	})
	if(res.data.openid){
		uni.setStorageSync("openid",res.data.openid)
		return res.data.openid
	}
	return ''
}

function getUrlCode() {
	let fullUrl = window.location.href;
	let theRequest = new Object();
	if (fullUrl.indexOf("?") != -1) {
		var temp = fullUrl.split("?");
		let str = temp[1];
		let strs = str.split("&");
		for (var i = 0; i < strs.length; i++) {
			theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
		}
	}
	return theRequest;
}
/**
 * 获取微信config
 */
export async function getWechatConfig() {
	const currentUrl = window.location.href;
	return request({
		method: "GET",
		data: {},
		url: '/wechat/config?url=' + currentUrl
	})
}
export function checkLogin() {
	const openid = uni.getStorageSync("openid")
	console.log("当前openid", openid)
	if (openid) {
		return
	}
	var pages = getCurrentPages();
	let currentPage = pages[pages.length - 1];
	// 获取当前页面的路由
	let currentRoute = currentPage.route;
	// 打印当前页面路径
	console.log("当前页面路径：" + currentRoute);
	uni.redirectTo({
		url: '/pages/login/login?backUrl=' + currentRoute
	})
}